package converter;

import exception.TypeConversionException;
import org.springframework.core.convert.converter.Converter;

import java.util.HashMap;
import java.util.Optional;

import static content.common.ExceptionMessage.PARAMS_ENUM_NOT_MATCH;

/**
 * String，Integer转换成枚举类型
 * @param <T>
 */
public class BaseToEnumConverter<T extends BaseEnum> implements Converter<String,T> {
    private HashMap<String,T> integerHashMap=new HashMap<>();
    private HashMap<String,T> stringHashMap=new HashMap<>();

    public BaseToEnumConverter(Class<T> enumType){
        T[] constants = enumType.getEnumConstants();
        for (T constant : constants) {
            integerHashMap.put(constant.getCode().toString(),constant);
            stringHashMap.put(constant.getName(),constant);
        }
    }

    @Override
    public T convert(String  source) {
        return Optional.of(source)
                .map(stringHashMap::get)
                .orElseGet(() -> Optional.of(source)
                        .map(integerHashMap::get)
                        .orElseThrow(() -> new TypeConversionException(PARAMS_ENUM_NOT_MATCH)));
    }
}
